package io.lkt.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.lkt.common.redis.RedisCacheUtil;
import io.lkt.common.utils.PageUtils;
import io.lkt.common.utils.Query;
import io.lkt.commons.dynamic.datasource.annotation.DataSource;
import io.lkt.modules.sys.dao.ArticleLookDetailLogDao;
import io.lkt.modules.sys.dao.BArticleInfoDao;
import io.lkt.modules.sys.dao.HeadlineTitleInfoDao;
import io.lkt.modules.sys.dao.SpiderTaskDao;
import io.lkt.modules.sys.entity.*;
import io.lkt.modules.sys.service.BArticleInfoService;
import io.lkt.modules.sys.service.BArticleTypeInfoService;
import io.lkt.modules.sys.service.BBrandInfoService;
import io.lkt.modules.sys.service.BUserInfoService;
import java.io.Serializable;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service("bArticleInfoService")
public class BArticleInfoServiceImpl
        extends ServiceImpl<BArticleInfoDao, BArticleInfoEntity>
        implements BArticleInfoService
{
    @Autowired
    BArticleTypeInfoService bArticleTypeInfoService;
    @Autowired
    BBrandInfoService bBrandInfoService;
    @Autowired
    private BUserInfoService bUserInfoService;
    @Autowired
    BArticleInfoDao bArticleInfoDao;
    @Autowired
    SpiderTaskDao spiderTaskDao;
    @Autowired
    RedisCacheUtil redisCacheUtil;

    @Autowired
    HeadlineTitleInfoDao headlineTitleInfoDao;

    @Autowired
    private ArticleLookDetailLogDao articleLookDetailLogDao;

    private int total;

    private int current;

    private String percent;

    private boolean flag;

    @Override
    @DataSource("master")
    public PageUtils queryPageForUserId(Map<String, Object> params) {

        IPage<BArticleInfoEntity> page = this.page(
                new Query<BArticleInfoEntity>().getPage(params),
                new QueryWrapper<BArticleInfoEntity>()
                        .eq("user_id", params.get("userId"))
                        .in("resource_type", Arrays.asList(1, 2))
                        .orderByDesc("id")
        );

        return new PageUtils(page);
    }

    public PageUtils queryPage(Map<String, Object> params)
    {
        IPage<BArticleInfoEntity> page = page(new Query()
                        .getPage(params),
                (Wrapper)new QueryWrapper().orderByDesc(new String[] { "id" }));
        for (BArticleInfoEntity bArticleInfoEntity : page.getRecords())
        {
            if (bArticleInfoEntity.getUserId() != null)
            {
                BUserInfoEntity bUserInfo = (BUserInfoEntity)this.bUserInfoService.getById(bArticleInfoEntity.getUserId());
                bArticleInfoEntity.setUserName(bUserInfo.getNickName());
            }
            else
            {
                bArticleInfoEntity.setUserName("管理员");
            }
            if (bArticleInfoEntity.getArticleTypeId() == null)
            {
                BBrandInfoEntity bBrandInfoEntity = this.bBrandInfoService.getById(bArticleInfoEntity.getArticleBrandId());
                if (bBrandInfoEntity != null) {
                    bArticleInfoEntity.setArticleTypeName(bBrandInfoEntity.getBrandName());
                }
            }
            else
            {
                BArticleTypeInfoEntity bArticleTypeInfoEntity = this.bArticleTypeInfoService.getById(bArticleInfoEntity.getArticleTypeId());
                if (bArticleTypeInfoEntity != null) {
                    bArticleInfoEntity.setArticleTypeName(bArticleTypeInfoEntity.getArticleTypeName());
                }
            }
        }
        return new PageUtils(page);
    }

    public Integer queryTotal(Map<String, Object> map)
    {
        List<Integer> brandIds=null;
        List<Integer> typeIds=null;
        if (map.get("articleTypeName").toString().length() > 0) {
            brandIds= bBrandInfoService.queryByNameLike(map.get("articleTypeName").toString());
            typeIds= bArticleTypeInfoService.queryByNameLike(map.get("articleTypeName").toString());
        }

        if(brandIds!=null && brandIds.size()>0) {
            map.put("brandIds", brandIds);
        }
        if(typeIds!=null && typeIds.size()>0) {
            map.put("typeIds", typeIds);
        }

        return this.bArticleInfoDao.queryTotal(map);
    }

    public List<BArticleInfoEntity> queryList(Map<String, Object> map)
    {
        List<Integer> brandIds=null;
        List<Integer> typeIds=null;
        if (map.get("articleTypeName").toString().length() > 0) {
            brandIds= bBrandInfoService.queryByNameLike(map.get("articleTypeName").toString());
            typeIds= bArticleTypeInfoService.queryByNameLike(map.get("articleTypeName").toString());
        }

        if(brandIds!=null && brandIds.size()>0) {
            map.put("brandIds", brandIds);
        }
        if(typeIds!=null && typeIds.size()>0) {
            map.put("typeIds", typeIds);
        }

        if(map.get("userGzhList")!=null) {
            List<SysUserGzhEntity> userGzhList = (List<SysUserGzhEntity>) map.get("userGzhList");
            if (userGzhList != null && userGzhList.size() == 1 && userGzhList.get(0).getGzhCode().equals("prodgjhkpt")) {//共建获客平台
                brandIds=new ArrayList<>();

                brandIds.add(41018);//共建集体
                brandIds.add(35456);//科技双特
                brandIds.add(27235);//聚多荣创
                brandIds.add(10840);//高佣联盟
                brandIds.add(52232);//黑卡优选
                map.put("brandIds", brandIds);
            }
        }

        return this.bArticleInfoDao.queryList(map);
    }

    public Integer titleTotal(String articleTitle, String brandId)
    {
        return this.bArticleInfoDao.titleTotal(articleTitle, brandId);
    }

    public List<BArticleInfoEntity> informArticel(Map<String, Object> map)
    {
        return this.bArticleInfoDao.informArticel(map);
    }

    public List<SpiderTaskEntity> getSpiderTaskList()
    {
        return this.spiderTaskDao.getList();
    }

    public SpiderTaskEntity getSpiderTaskById(Integer id)
    {
        return this.spiderTaskDao.getSpiderTaskById(id);
    }

    public void updateImportStute(Integer id)
    {
        this.spiderTaskDao.updateImportStute(id);
    }

    public void setNullArticleBrandId(Integer id)
    {
        this.bArticleInfoDao.setNullArticleBrandId(id);
    }

    public void setNullArticleTypeId(Integer id)
    {
        this.bArticleInfoDao.setNullArticleTypeId(id);
    }

    public Integer informArticelTotal(Map<String, Object> map)
    {
        return this.bArticleInfoDao.informArticelTotal(map);
    }

    public List<BArticleInfoEntity> queryArticleInfoByArticleBrandForHotScore(Integer articleBrandId, Integer recordSize)
    {
        return this.bArticleInfoDao.queryArticleInfoByArticleBrandForHotScore(articleBrandId, recordSize);
    }

    public List<BArticleInfoEntity> queryArticleInfoByArticleTypeForHotScore(Integer articleTypeId, Integer recordSize)
    {
        return this.bArticleInfoDao.queryArticleInfoByArticleBrandForHotScore(articleTypeId, recordSize);
    }

    @DataSource("master")
    public BArticleInfoEntity getById(Serializable id)
    {
        return (BArticleInfoEntity)((BArticleInfoDao)this.baseMapper).selectById(id);
    }

    @DataSource("master")
    public boolean save(BArticleInfoEntity entity)
    {
        return retBool(Integer.valueOf(((BArticleInfoDao)this.baseMapper).insert(entity)));
    }

    @DataSource("master")
    public boolean updateById(BArticleInfoEntity entity)
    {
        return retBool(Integer.valueOf(((BArticleInfoDao)this.baseMapper).updateById(entity)));
    }

    @Override
    public void updateSourceHeight(Integer id, Integer height) {
        this.bArticleInfoDao.updateSourceHeight(id, height);
    }

    @Override
    public void headlineRelation(Integer articleId, List<Integer> headlineTitleIds,Integer userId) {
        headlineTitleIds.stream().forEach(headlineTitleId ->{
            this.headlineTitleInfoDao.headlineRelation(articleId,headlineTitleId,userId);
        });
    }

    @Override
    public List<Integer> selectHeadlineIdsByArticleId(Integer id) {
        return this.headlineTitleInfoDao.selectHeadlineIdsByArticleId(id);
    }

    @Override
    public void delHeadlineRelation(Integer id) {
        this.headlineTitleInfoDao.delHeadlineRelation(id);
    }

    @Override
    public List<BUserShareArticleInfoEntity> getUserCopyInfo(Map<String, Object> params) {
        return bArticleInfoDao.getUserCopyInfo(params);
    }

    @Override
    public int getUserCopyInfoTotal(Map<String, Object> params) {
        return bArticleInfoDao.getUserCopyInfoTotal(params);
    }

    @Override
    public int getUserArticleCount(Integer userId) {
        return bArticleInfoDao.getUserArticleCount(userId);
    }

    @Override
    public void updateArticleDesc(String articleDesc, String[] articleNewDesc, Integer type) {
        if (type == 1) {
            this.recover();
            List<BArticleInfoEntity> descList = bArticleInfoDao.queryArticleInfoByDesc(articleDesc);

            if (descList != null && descList.size() > 0) {
                this.total = descList.size();

                for (BArticleInfoEntity bArticleInfo : descList) {
                    int index = (int) (Math.random() * articleNewDesc.length);
                    String randomArticleDesc = articleNewDesc[index];

                    String title = bArticleInfo.getArticleTitle().replace(articleDesc, randomArticleDesc);
                    String desc = bArticleInfo.getArticleDesc().replace(articleDesc, randomArticleDesc);

                /*for (String emoji : emoji_arr) {
                    if (title.contains(emoji)) {
                        title=title.replace(emoji, "");
                    }
                    if (desc.contains(emoji)) {
                        desc=desc.replace(emoji, "");
                    }
                }*/

                    bArticleInfo.setArticleTitle(title);
                    bArticleInfo.setArticleDesc(desc);

                    this.updateById(bArticleInfo);
                    String cacheKey = bArticleInfo.getId() + "ArticleDetailInfoKey";

                    this.redisCacheUtil.removeSingleCacheMaster(cacheKey);
                    System.out.println("***** updateTitle:ID=" + bArticleInfo.getId() + " _ Desc:" + desc);
                    this.increase();
                }
            } else {
                this.flag = true;
            }
        } else if (type == 2) {
            this.recover();
            List<BArticleInfoEntity> titleList = bArticleInfoDao.queryArticleInfoByTitle(articleDesc);

            if (titleList != null && titleList.size() > 0) {
                this.total = titleList.size();

                for (BArticleInfoEntity bArticleInfo : titleList) {

                    int index = (int) (Math.random() * articleNewDesc.length);
                    String randomArticleDesc = articleNewDesc[index];

                    String title = bArticleInfo.getArticleTitle().replace(articleDesc, randomArticleDesc);
                    String desc = bArticleInfo.getArticleDesc().replace(articleDesc, randomArticleDesc);

                /*for (String emoji : emoji_arr) {
                    if (title.contains(emoji)) {
                        title=title.replace(emoji, "");
                    }
                    if (desc.contains(emoji)) {
                        desc=desc.replace(emoji, "");
                    }
                }*/

                    bArticleInfo.setArticleTitle(title);
                    bArticleInfo.setArticleDesc(desc);

                    this.updateById(bArticleInfo);
                    String cacheKey = bArticleInfo.getId() + "ArticleDetailInfoKey";

                    this.redisCacheUtil.removeSingleCacheMaster(cacheKey);
                    System.out.println("***** updateTitle:ID=" + bArticleInfo.getId() + " _ Title:" + title + " _ Desc:" + desc);
                    this.increase();
                }
            } else {
                this.flag = true;
            }
        }
    }

    @Override
    public void updateArticleContent(Integer brandId, String content, String[] newContents) {
        recover();
        List<BArticleInfoEntity> articleList = bArticleInfoDao.queryArticleInfoByBrandId(brandId);

        if (articleList != null && articleList.size() > 0) {
            this.total = articleList.size();

            for (BArticleInfoEntity bArticleInfo : articleList) {
                int index = (int) (Math.random() * newContents.length);
                String randomNewContent = newContents[index];

                try {
                    BArticleInfoEntity articleInfoEntity = bArticleInfoDao.selectById(bArticleInfo.getId());

                    if (articleInfoEntity != null && articleInfoEntity.getArticleContent() != null && articleInfoEntity.getArticleContent().contains(content)) {

                        String c =articleInfoEntity.getArticleContent().replace(content, randomNewContent);
                        bArticleInfo.setArticleContent(c);
                        this.updateById(bArticleInfo);

                        String cacheKey = bArticleInfo.getId() + "ArticleDetailInfoKey";

                        this.redisCacheUtil.removeSingleCacheMaster(cacheKey);
                        System.out.println("***** updateTitle:ID=" + bArticleInfo.getId());
                    }
                }catch (Exception e){

                }
                increase();
            }
        } else {
            this.flag = true;
        }
    }

    @Override
    public void deleteHalfYearAgoArticle() {
        recover();
        List<BArticleInfoEntity> notLooks = bArticleInfoDao.queryArticleInfoByTop20200630();

        Integer delCount = 0;
        Integer chuliCount = 0;

        Integer imgCount = 0;
        Integer videoCount = 0;
        Integer audioCount = 0;

        if (notLooks != null && notLooks.size() > 0) {
            this.total = notLooks.size();

            for (BArticleInfoEntity a : notLooks) {
                chuliCount++;
                Integer lookCount = articleLookDetailLogDao.getArticleLookDetailLog(a.getId());
                System.out.println("ArticleId:" + a.getId() + "___lookCount:" + lookCount);
                if (lookCount.equals(0)) {

//                Document document = null;
//                BArticleInfoEntity ac= bArticleInfoDao.selectById(a.getId());
//                document = Jsoup.parse(ac.getArticleContent());
//
//                Elements imgElements = document.select("img");
//
//                for (Element img : imgElements) {
//                    String fileKey = "";
//                    if ((img.attr("src") != null)) {
//                        String src = img.attr("src");
//                        if (src.contains("/ps/")) {
//                            fileKey = src.substring(src.indexOf("ps"));
//                        } else if (src.contains("/webSpiderImg/")) {
//                            fileKey = src.substring(src.indexOf("webSpiderImg"));
//                        }
//                        if(!fileKey.equals("")) {
//                            AliyunOssClientUtil.delFile(fileKey);
//                            imgCount++;
//                        }
//                    }
//                }
//
//                Elements videoElements = document.select("video");
//                for (Element video : videoElements) {
//                    String fileKey = "";
//                    if ((video.attr("src") != null)) {
//                        String src = video.attr("src");
//                        if (src.contains("/ps/")) {
//                            fileKey = src.substring(src.indexOf("ps"));
//                        } else if (src.contains("/webSpiderVideo/")) {
//                            fileKey = src.substring(src.indexOf("webSpiderVideo"));
//                        }
//                        if(!fileKey.equals("")) {
//                            AliyunOssClientUtil.delFile(fileKey);
//                            videoCount++;
//                        }
//                    }
//                }
//
//                Elements audioElements = document.select("audio");
//                for (Element audio : audioElements) {
//                    String fileKey = "";
//                    if ((audio.attr("src") != null)) {
//                        String src = audio.attr("src");
//                        if (src.contains("/ps/")) {
//                            fileKey = src.substring(src.indexOf("ps"));
//                        } else if (src.contains("/webSpiderAudio/")) {
//                            fileKey = src.substring(src.indexOf("webSpiderAudio"));
//                        }
//                        if(!fileKey.equals("")) {
//                            AliyunOssClientUtil.delFile(fileKey);
//                            audioCount++;
//                        }
//                    }
//                }

                    bArticleInfoDao.delArticle(a.getId());
                    delCount++;
                    System.out.println("Delete:" + a.getId() + "___delCount:" + delCount);

                } else {
                    System.out.println("NotDelete:" + a.getId() + "___lookCount:" + lookCount);
                }
                increase();
            }
        } else {
            this.flag = true;
        }
    }

    @Override
    public BArticleInfoEntity getLatestArticleByBranbId(Integer brandId) {
        return bArticleInfoDao.getLatestArticleByBranbId(brandId);
    }

    @Override
    public BArticleInfoEntity getBeginnerArticleById(Integer id) {
        return bArticleInfoDao.getBeginnerArticleById(id);
    }

    @Override
    public Map<String, Object> getProgressInfo() {
        Map<String, Object> map = new HashMap<>();
        map.put("total", this.total);
        map.put("current", this.current);
        map.put("percent", this.percent);
        map.put("flag", this.flag);
        return map;
    }

    private void recover() {
        this.total = 0;
        this.current = 0;
        this.percent = "0";
        this.flag = false;
    }

    private void increase() {
        this.current++;
        double result = (this.current * 10000) / total;
        this.percent = new BigDecimal(result / 100).setScale(2, RoundingMode.HALF_UP).toString();
    }
}
